package com.weigecoder.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weigecoder.entity.ShopType;
import com.weigecoder.mapper.ShopTypeMapper;
import com.weigecoder.service.IShopTypeService;
import com.weigecoder.utils.CacheClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.weigecoder.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;
import static com.weigecoder.utils.RedisConstants.CACHE_SHOP_TYPE_TTL;

@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private CacheClient cacheClient;

    @Override
    public List<ShopType> queryTypeList() {
        List<ShopType> shopTypes = null;
        String shopTypes_cache = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
        if (!StringUtils.hasText(shopTypes_cache)){  // 缓存不存在
            LambdaQueryWrapper<ShopType> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.orderByAsc(ShopType::getSort);
             shopTypes = baseMapper.selectList(queryWrapper);
             stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY, JSONUtil.toJsonStr(shopTypes), CACHE_SHOP_TYPE_TTL, TimeUnit.DAYS);
        }
        //从缓存中获取商户类型
        shopTypes = JSONUtil.toList(shopTypes_cache, ShopType.class);

        return shopTypes;
    }
}
